﻿@using Gurux.DLMS.AMI.Shared.DIs

@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using Gurux.DLMS.AMI.Shared.DTOs.Authentication
@using Gurux.DLMS.AMI.Shared.DTOs
@using Gurux.DLMS.AMI.Shared.Rest
@using Gurux.DLMS.AMI.Shared.Enums
@using Gurux.DLMS.AMI.Client.Helpers
@using Gurux.DLMS.AMI.Module

@attribute [Authorize(Roles = "Admin, DeviceGroupManager")]
@inject NavigationManager NavigationManager
@inject HttpClient Http
@inject IGXNotifier2 Notifier

@if (Active != null)
{
    <EditForm Model="@Active">
        <DataAnnotationsValidator />
        <ValidationSummary />
        <div class="row">
            <div style="width:100%">
                <div class="form-group">
                    <label>@Properties.Resources.Name</label>
                    <InputText id="name" disabled="@IsDeleting" class="form-control"
                           @bind-Value="Active.Name" />
                </div>
                <div class="form-group">
                    <InputNullableSwitch 
                        Text="@Properties.Resources.DefaultGroup" 
                        @bind-Value="Active.Default" />
                    <br />
                </div>
                <div class="form-group">
                    <label>@Properties.Resources.Description</label>
                    <InputText id="name" disabled="@IsDeleting" class="form-control"
                           @bind-Value="Active.Description" />
                </div>
            </div>
            @if (Active.CreationTime != DateTime.MinValue)
            {
                <div class="form-group">
                    <label>@Properties.Resources.CreationTime</label>
                    <InputDate Type="@InputDateType.DateTimeLocal" id="generation" readonly="readonly" class="form-control"
                       @bind-Value="Active.CreationTime" />
                </div>
            }
            @if (Active.Updated != null)
            {
                <div class="form-group">
                    <label>@Properties.Resources.Updated</label>
                    <InputDate Type="@InputDateType.DateTimeLocal" id="generation" readonly="readonly" class="form-control"
                       @bind-Value="Active.Updated" />
                </div>
            }
            @if (Active.Removed != null)
            {
                <div class="form-group">
                    <label>@Properties.Resources.Removed</label>
                    <InputDate Type="@InputDateType.DateTimeLocal" id="removed" class="form-control"
                       @bind-Value="Active.Removed" />
                </div>
            }
            @if (action == CrudAction.Delete)
            {
                <hr />
                <p>
                </p>
                <div class="form-group">
                    <InputRadioGroup @bind-Value="DeleteTarget">
                        <InputRadio Value="false">
                        </InputRadio>
                        <label>@Properties.Resources.TargetDisableQuestion</label><br>
                        <InputRadio Value="true">
                        </InputRadio>
                        <label>@Properties.Resources.TargetDeleteQuestion</label>
                    </InputRadioGroup>
                    <br />
                </div>
            }
        </div>
    </EditForm>
}

@code {

    [CascadingParameter]
    private DeviceGroupTab? Parent { get; set; }

    private GXDeviceGroup? _active;

    private GXDeviceGroup? Active
    {
        get
        {
            if (Parent?.Active != null)
            {
                return Parent.Active;
            }
            return _active;
        }
    }

    /// <summary>
    /// User action.
    /// </summary>
    [Parameter]
    public string? Action { get; set; }

    private CrudAction action;
    /// <summary>
    /// Selected item.
    /// </summary>
    [Parameter]
    public Guid? Id { get; set; }

    private bool DeleteTarget;
    public string? IsDeleting
    {
        get
        {
            if (Notifier.Action != CrudAction.Delete)
            {
                return null;
            }
            return "disabled";
        }
    }


    protected override async Task OnInitializedAsync()
    {
        try
        {
            Notifier.ProgressStart();
            Notifier.ClearStatus();
            Notifier.Clear();
            if (Active == null && Id != null)
            {
                //Get device group data.
                var tmp = (await Http.GetAsJsonAsync<GetDeviceGroupResponse>(string.Format("api/DeviceGroup?id={0}", Id)));
                if (tmp?.Item != null)
                {
                    _active = tmp.Item;
                }
                else
                {
                    NavigationManager.NavigateTo("404");
                }
            }
            if (Active == null)
            {
                throw new ArgumentException(Properties.Resources.InvalidTarget);
            }
            action = ClientHelpers.GetAction(Action);
            if (action == CrudAction.Delete)
            {
                Notifier.AddMenuItem(new GXMenuItem() { Text = Properties.Resources.Remove, Icon = "oi oi-trash", OnClick = OnSave });
            }
            else
            {
                Notifier.AddMenuItem(new GXMenuItem() { Text = Properties.Resources.Save, Icon = "oi oi-pencil", OnClick = OnSave });
            }
            Notifier.AddMenuItem(new GXMenuItem() { Text = Properties.Resources.Cancel, Icon = "oi oi-action-undo", OnClick = OnCancel });
            Notifier.UpdateButtons();
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
        finally
        {
            Notifier?.ProgressEnd();
        }
    }

    /// <summary>
    /// Save device group.
    /// </summary>
    public async void OnSave()
    {
        try
        {
            if (Active == null)
            {
                throw new Exception(Properties.Resources.InvalidTarget);
            }
            Notifier.ProgressStart();
            Notifier.ClearStatus();
            if (action == CrudAction.Delete)
            {
                await Http.PostAsJson<RemoveDeviceGroupResponse>("api/DeviceGroup/Delete", new RemoveDeviceGroup()
                    {
                        Ids = new Guid[] { Active.Id },
                        Delete = DeleteTarget
                    });
            }
            else
            {
                string address;
                if (action == CrudAction.Create)
                {
                    address = "api/DeviceGroup/Add";
                }
                else if (action == CrudAction.Update)
                {
                    address = "api/DeviceGroup/Update";
                }
                else
                {
                    throw new Exception(Properties.Resources.InvalidTarget);
                }
                await Http.PostAsJson<AddDeviceGroupResponse>(address, new AddDeviceGroup() { DeviceGroups = new GXDeviceGroup[] { Active } });
            }
            ClientHelpers.NavigateToLastPage(NavigationManager, Notifier);
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
        finally
        {
            Notifier?.ProgressEnd();
        }
    }

    /// <summary>
    /// Cancel update.
    /// </summary>
    private void OnCancel()
    {
        ClientHelpers.NavigateToLastPage(NavigationManager, Notifier);
    }
}
